package com.voicechat.firstmet.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.ShareGirlsAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PersonDataBean;
import com.voicechat.firstmet.bean.ShareGirlsBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.FaintService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity
 * @ClassName: MySharePhotoActivity
 * @Description: 我的共享闺蜜页面
 * @Author: ljp
 * @CreateDate: 2019/1/17 19:29
 * @Version: 1.0
 */
public class MyShareGirlsActivity extends BaseActivity {

    @BindView(R.id.recycler_list)
    RecyclerView recyclerList;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_uploading)
    TextView tvUploading;
    @BindView(R.id.image_delete)
    ImageView imageDelete;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String deviceInfo;
    private ShareGirlsAdapter shareGirlsAdapter;
    private List<ShareGirlsBean.PageBean.ListBean> tlist;
    private int page = 1;
    private String TAG = "MyShareGirlsActivity";

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_my_share_photo;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        initView();
    }

    private void initView() {
        tvTitle.setText("我的闺蜜");
        page = 1;
        tlist = new ArrayList<>();
        smartRefresh.autoRefresh();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                initHttpData();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initHttpData();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        shareGirlsAdapter = new ShareGirlsAdapter(context, tlist, R.layout.item_share_girls, "me");
        recyclerList.setLayoutManager(new GridLayoutManager(activity, 2));
        recyclerList.setAdapter(shareGirlsAdapter);
        shareGirlsAdapter.setItemClick(new ShareGirlsAdapter.ItemClick() {
            @Override
            public void setItemClick(int position, ShareGirlsBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(activity, ShareGirlsDetailsActivity.class);
                intent.putExtra("id", listBean.getId());
                context.startActivity(intent);
            }
        });
        initHttpData();
    }
    /**
     * @return
     * @method
     * @description 请求网络信息
     * @date: 2019/1/17 19:08
     * @author: ljp
     */
    private void initHttpData() {
        FaintService.shareMyGirlsSelect(token, deviceInfo, page, mySeleInfo.getId(), "").subscribe(shareGirlsBean -> {
            Log.i(TAG, "initHttp: ----------" + shareGirlsBean.toString());
            if (shareGirlsBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = shareGirlsBean.getPage().getCount() / shareGirlsBean.getPage().getPageSize() +
                        (shareGirlsBean.getPage().getCount() % shareGirlsBean.getPage().getPageSize() == 0 ? 0 : 1);
                if (i != 0 && page > i) {//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        if (shareGirlsBean.getPage().getList() == null) {
                            imageDelete.setVisibility(View.GONE);
                        }
                        tlist.clear();
                        smartRefresh.finishRefresh();
                        isSureDelete = 0;
                        imageDelete.setImageResource(R.mipmap.photo_delete);
                        tvUploading.setText("上传");
                    }
                    if (shareGirlsBean.getPage().getList() != null) {
                        if (isSureDelete == 1) {
                            for (int n = 0; n < shareGirlsBean.getPage().getList().size(); n++) {
                                shareGirlsBean.getPage().getList().get(n).setSelectDelete(-1);
                            }
                        }
                        tlist.addAll(shareGirlsBean.getPage().getList());
                        shareGirlsAdapter.notifyDataSetChanged();
                    } else {
                    }
                    smartRefresh.finishLoadMore();
                }
            } else if (shareGirlsBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(shareGirlsBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "initHttp: ----------" + throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });


    }

    private int isSureDelete = -1;//是删除还是选定 -1选定  1删除 0取消选定

    @OnClick({R.id.linear_back, R.id.tv_uploading, R.id.image_delete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                finish();
                break;
            case R.id.tv_uploading:
                //取消删除
                if (isSureDelete == 1) {
                    shareGirlsAdapter.getSb().clear();
                    isSureDelete = 0;
                    imageDelete.setImageResource(R.mipmap.photo_delete);
                    for (int j = 0; j < tlist.size(); j++) {
                        tlist.get(j).setSelectDelete(0);
                    }
                    shareGirlsAdapter.notifyDataSetChanged();
                    tvUploading.setText("上传");
                } else {
                    //是会员用户并且已经实名认证，才可以发布
                    // 会员类型  0非会员 1月会员 2年会员
                    if(mySeleInfo.getvType().equals("1") || mySeleInfo.getvType().equals("2")){
                        //判断是否实名认证
                        if (mySeleInfo.getIsAttestation() == 0) {// 实名认证任务 0未认证 1 已审核 2 审核中 3驳回
                            toast_MakeText(getResources().getString(R.string.realName_hint));
                        }else {
                            judeRealName();
                        }
                    }else {
                        toast_MakeText(getResources().getString(R.string.vip_text));
                    }

                }
                break;
            case R.id.image_delete:
                if (isSureDelete == -1 || isSureDelete == 0) {
                    tvUploading.setText("取消");
                    imageDelete.setImageResource(R.mipmap.photo_sure);
                    //onClickDelete.setDelete(isSureDelete);
                    isSureDelete = 1;
                    for (int i = 0; i < tlist.size(); i++) {
                        tlist.get(i).setSelectDelete(-1);
                    }
                    shareGirlsAdapter.notifyDataSetChanged();
                } else {
                    if (shareGirlsAdapter.getSb().size() != 0) {
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int i = 0; i < shareGirlsAdapter.getSb().size(); i++) {
                            stringBuffer.append(shareGirlsAdapter.getSb().get(i) + ",");
                        }
                        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                        showCacheDialog(stringBuffer.toString());
                    } else {
                        toast_MakeText("请选择删除照片");
                    }
                }
                break;
        }
    }
    /**
     * @method
     * @description 判断是否实名认证
     * @date: 2019/1/28 13:45
     * @author: ljp
     * @return
     */
    private void judeRealName(){
        MeInfoService.certificationSelect(mySeleInfo.getId(), token, deviceInfo).subscribe(personDataBean -> {
            if (personDataBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                //判断state状态  认证状态 0审核中 1审核通过 2驳回
                PersonDataBean.ObjectBean object = personDataBean.getObject();
                if (object.getStatus() == 0) {
                    toast_MakeText(getResources().getString(R.string.real_name));
                } else if (object.getStatus() == 1) {
                    startActivity(new Intent(activity, PublishShareGirlsActivity.class));
                    finish();
                } else {
                    toast_MakeText(getResources().getString(R.string.realName_hint));
                }
            } else if (personDataBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(personDataBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "judeRealName: ---------" + throwable.toString());
        });
    }
    /**
     * @return
     * @method
     * @description 删除照片
     * @date: 2018/11/1 19:37
     * @author: ljp
     */
    private void showCacheDialog(String string) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(context);
        normalDialog.setMessage("确认删除?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                        deleteAlbum(string);
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * @return
     * @method
     * @description 删除共享闺蜜
     * @date: 2018/12/21 16:01
     * @author: ljp
     */
    private void deleteAlbum(String string) {
        FaintService.deleteShareGirls(token, deviceInfo, string).subscribe(result -> {
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                smartRefresh.autoRefresh();
                toast_MakeText("删除成功");
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }

}
